package com.price.sample.ui

import android.os.Bundle
import com.price.common.extend.doOnClick
import com.price.common.extend.launch
import com.price.common.util.formatTime
import com.price.common.viewbinding.base.BaseBindingActivity
import com.price.httplib.websocket.WebSocketBuilder
import com.price.httplib.websocket.MyWebSocketListener
import com.zp.common.databinding.ActivitySocketBinding
import kotlinx.coroutines.Dispatchers

class SocketActivity : BaseBindingActivity<ActivitySocketBinding>() {

    override fun onCreated(savedInstanceState: Bundle?) {
        val mListener=object :MyWebSocketListener(){
            override fun onStatus(url:String,code: Int) {
                launch(Dispatchers.Main) {
                    binding.tvMsg.text = buildString {
                        append(binding.tvMsg.text.toString())
                        append("\n")
                        append("status:$code")
                    }
                }
            }
            override fun onMessage(url:String,msg: String) {
                launch(Dispatchers.Main) {
                    binding.tvMsg.text = buildString {
                        append(binding.tvMsg.text.toString())
                        append("\n")
                        append(System.currentTimeMillis().formatTime())
                        append(" ")
                        append(msg)
                    }
                }
            }
        }
        val webSocketManager = WebSocketBuilder
            .build {
                reConnect=true
                url = "ws://20.2.82.219:9001"
                heart = "heart"
                listener=mListener
            }
        val webSocketManager1 = WebSocketBuilder
            .build {
                url = "ws://124.222.224.186:8800"
                heart = "heart123"
                listener=mListener
            }
        binding.btnConnect.doOnClick {
            webSocketManager.connect()
        }
        binding.btnClose.doOnClick {
            webSocketManager.close()
        }

    }
}